<?php

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;
use app\api\service\Token;
use app\api\validate\IDMustBePositiveInt;
use app\api\validate\OrderPlace;
use app\api\validate\PagingParameter;
use app\api\exception\OrderException;
use app\api\exception\SuccessMessage;
use think\Controller;

class Order extends BaseController
{

    protected $beforeActionList = [
        'checkExclusiveScope' => [ 'only' => 'placeOrder' ],
        'checkPrimaryScope' => [ 'only' => 'getDetail,getSummaryByUser' ],
        'checkSuperScope' => [ 'only' => 'delivery,getSummary' ]
    ];

    /**
     * 下单
     * @url /order
     * @HTTP POST
     */
    public function placeOrder()
    {
        (new OrderPlace())->goCheck();
        $uid = Token::getCurrentUid();
        $order_products = input('products');
//        $redis_model = new \Redis();
//        $redis_model->connect('127.0.0.1', 6379);
//        if (!empty($redis_model->lPop('stock')))
//        {
            $order_server = new OrderService($uid, $order_products);
            $res = $order_server->place();
//        }
//        else
//        {
//            throw new OrderException();
//        }
        return $res;
    }

    public function test($token = '')
    {
        $redis_model = new \Redis();
        $redis_model->connect('127.0.0.1');
        for ($i = 0; $i < 100; $i++)
        {
            $redis_model->rPush('stock',1);
        }
        halt_plus($redis_model->lLen('stock'));
        for ($i = 0; $i < 200; $i++)
        {
            $param = [
                'products' => [
                    [ 'product_id' => 1, 'count' => 1 ],
                    [ 'product_id' => 2, 'count' => 1 ],
                ],
            ];
            if (!empty($token))
            {
                $token = '7B82BF4F4E04AD1999417E6E5B2C2EC5';
            }
            $res = curl_post('https://www.liveknight.xyz/api/v1/order', $param, $token);
        }
    }

    /**
     * 获取订单详情
     * @param $id
     * @return static
     * @throws OrderException
     * @throws \app\lib\exception\ParameterException
     */
    public function getDetail($id)
    {
        (new IDMustBePositiveInt())->goCheck();
        $orderDetail = OrderModel::get($id);
        if (!$orderDetail)
        {
            throw new OrderException();
        }
        return $orderDetail->hidden([ 'prepay_id' ]);
    }

    /**
     * 根据用户id分页获取订单列表（简要信息）
     * @param int $page
     * @param int $size
     * @return array
     * @throws \app\lib\exception\ParameterException
     */
    public function getSummaryByUser($page = 1, $size = 15)
    {
        ( new PagingParameter())->goCheck();
        $uid = Token::getCurrentUid();
        $paging_orders = OrderModel::getSummaryByUser($uid, $page, $size);
        if ($paging_orders->isEmpty())
        {
            return [
                'current_page' => $paging_orders->currentPage(),
                'data' => []
            ];
        }
        $data = $paging_orders->hidden([ 'snap_items', 'snap_address' ])
                ->toArray();
        return [
            'current_page' => $paging_orders->currentPage(),
            'data' => $data
        ];
    }

    /**
     * 获取全部订单简要信息（分页）
     * @param int $page
     * @param int $size
     * @return array
     * @throws \app\lib\exception\ParameterException
     */
    public function getSummary($page = 1, $size = 20)
    {
        (new PagingParameter)->goCheck();
        $paging_orders = OrderModel::getSummaryByPage($page, $size);
        if ($paging_orders->isEmpty())
        {
            return [
                'current_page' => $paging_orders->currentPage(),
                'data' => []
            ];
        }
        $data = $paging_orders->hidden([ 'snap_items', 'snap_addres' ])->toArray();
        return [
            'current_page' => $paging_orders->currentPage(),
            'data' => $data
        ];
    }

    /**
     * 更新订单快递状态并推送消息
     * @param type $id
     * @return SuccessMessage
     */
    public function delivery($id)
    {
        (new IDMustBePositiveInt)->goCheck();
        $order_server = new OrderService();
        $success = $order_server->delivery($id);
        if ($success)
        {
            return new SuccessMessage();
        }
        throw new OrderException();
    }

}
